import { defineComponent, ref, reactive, onMounted, onUnmounted } from "vue";
import TablePage from "@/components/TablePage/TablePage";
import { tablesInterface } from "@/common/interface/table.interface";
import MusicScoreService from "./index.service";
import MusicSongCategoryService from "@/views/musicScore/category/index.service";
import to from "await-to-js";
import Add from "./Add/Add";
import { message, Modal } from "ant-design-vue";
import styles from "./index.module.less";
import JsonPreview from "@/components/JsonPreview/JsonPreview";
import { useRouter } from "vue-router";
import eventBus from "@/common/eventBus/mitt";
import approveStatus from "@/common/dicts/approveStatus";
import { analysisPermissionsAndOr } from "@/common/auth/auth";
// 是否热门switch
const IsRecommendSwitch = defineComponent({
  props: {
    record: {
      type: Object,
    },
    value: {
      type: Number,
    }
  },
  emits: ["change"],
  setup(props: any, { emit }) {
    const musicScoreService = new MusicScoreService();
    const loading = ref(false);
    const isRecommendChange = async (e) => {
      loading.value = true;
      const [err, res]: any = await to(musicScoreService.isRecommendChange({
        record: props.record,
        isRecommend: e,
      }));
      if (!err) {
        message.success("修改成功!");
        emit("change");
      }
      loading.value = false;
    }
    return () => <>
      {
        analysisPermissionsAndOr("music:song:edit") ? <a-switch loading={loading.value} checked={props.value} checkedValue={1} unCheckedValue={0} onChange={(e) => { isRecommendChange(e) }} /> : <span>{props.value === 1 ? "是" : "否"}</span>
      }
    </>
  }
})
// 审核状态
const ApproveStatus = defineComponent({
  props: {
    text: {
      type: Number,
    }
  },
  setup(props: any) {
    return () => (
      <span class={[styles['approve-status'], styles[`approve-status-${approveStatus.find(x => x.value === props.text)?.color}`]]}>{approveStatus.find(x => x.value === props.text)?.label || ""}</span>
    )
  }
})
const StatusSwitch = defineComponent({
  props: {
    record: {
      type: Object,
    },
    value: {
      type: Number,
    }
  },
  emits: ["change"],
  setup(props: any, { emit }) {
    const musicScoreService = new MusicScoreService();
    const loading = ref(false);
    const statusChange = async (e) => {
      if (!props.record.lyricsData) {
        message.error("请先打谱,待完成后再次上架!");
        return;
      }
      if (e === 1) {
        const modalConfirm = async () => {
          return new Promise((resolve) => {
            Modal.confirm({
              title: "提示",
              content: "上架后需重新提交审核，确认下架?",
              onOk: () => {
                resolve(true);
              },
              onCancel: () => {
                resolve(false);
              }
            })
          })
        }
        if (!await modalConfirm()) {
          return;
        }
      }
      loading.value = true;
      const [err, res]: any = await to(musicScoreService.statusChange({
        record: props.record,
        status: e,
      }));
      if (!err) {
        e === 0 ? message.success("上架成功!") : message.success("下架成功!");
        emit("change");
      }
      loading.value = false;
    }
    return () => <>
      {
        analysisPermissionsAndOr("music:song:status") ? <a-switch disabled={![2].includes(props.record.approveStatus)} v-permissions="music:song:status" loading={loading.value} checked={props.value} checkedValue={0} unCheckedValue={1} onChange={(e) => { statusChange(e) }} /> : <span>{props.value === 0 ? "已开启" : "已关闭"}</span>
      }
    </>
  }
})
const ToExamineSwitch = defineComponent({
  props: {
    record: {
      type: Object,
    },
    value: {
      type: Number,
    }
  },
  emits: ["change"],
  setup(props: any, { emit }) {
    const musicScoreService = new MusicScoreService();
    const loading = ref(false);
    const toExamineChange = async (e) => {
      loading.value = true;
      const [err, res]: any = await to(musicScoreService.toExamineChange({
        record: props.record,
        toExamine: e,
      }));
      if (!err) {
        message.success("变更成功!");
        emit("change");
      }
      loading.value = false;
    }
    return () => <>
      {
        analysisPermissionsAndOr("music:song:edit") ? <a-switch v-permissions="music:song:edit" loading={loading.value} checked={props.value} checkedValue={1} unCheckedValue={0} onChange={(e) => { toExamineChange(e) }} /> : <span>{props.value === 1 ? "是" : "否"}</span>
      }
    </>
  }
})
const Remark = defineComponent({
  props: {
    text: {
      type: String,
    },
  },
  setup(props: any) {
    const arr = props?.text?.split?.(",") || [];
    return () => <span>
      {
        arr.map((item) => `和弦${item}暂未导入`).join(",")
      }
    </span>
  }
})
export default defineComponent({
  name: "List",
  setup() {
    const router = useRouter();
    const tablePageRef = ref(null as any);
    const musicScoreService = new MusicScoreService();
    const musicSongCategoryService = new MusicSongCategoryService();
    // 表格定义
    const tables = reactive({
      list: [
        {
          title: "曲谱管理",
          rowKey: "id",
          columns: [
            {
              title: "ID",
              dataIndex: "id",
              align: "center",
              width: "80px",
            },
            {
              title: "曲谱名称",
              dataIndex: "name",
              align: "center",
              width: "280px",
            },
            {
              title: "审核状态",
              dataIndex: "approveStatus",
              align: "center",
              width: "180px",
            },
            {
              title: "开启状态",
              dataIndex: "status",
              align: "center",
              width: "180px",
            },
            {
              title: "曲谱分类",
              dataIndex: "cate",
              align: "center",
              width: "180px",
            },
            {
              title: "作者",
              dataIndex: "author",
              align: "center",
              width: "180px",
            },
            {
              title: "是否热门",
              dataIndex: "isRecommend",
              align: "center",
              width: "120px",
            },
            {
              title: "是否旋律谱",
              dataIndex: "isMelody",
              align: "center",
              width: "120px",
            },
            {
              title: "排序",
              dataIndex: "sort",
              align: "center",
              width: "180px",
            },
            {
              title: "曲谱调",
              dataIndex: "scoreTone",
              align: "center",
              width: "100px",
            },
            {
              title: "和弦调",
              dataIndex: "chordTone",
              align: "center",
              width: "100px",
            },
            {
              title: "打谱内容",
              dataIndex: "lyricsData",
              align: "center",
              width: "120px",
            },
            {
              title: "xml文件",
              dataIndex: "xmlFile",
              align: "center",
              width: "280px",
            },
            {
              title: "mid文件",
              dataIndex: "midFile",
              align: "center",
              width: "280px",
            },
            {
              title: "备注",
              dataIndex: "remark",
              align: "center",
              width: "280px",
            },
            {
              title: "是否审核用",
              dataIndex: "toExamine",
              align: "center",
              width: "180px",
            },
          ],
          toolbar: {
            left: ["refresh", "add"],
            right: ["filter", "search"],
            add: {
              permissions: "music:song:add",
              handler: () => {
                const addPopupRef = tablePageRef.value.getPopup("addRef");
                addPopupRef.value.open({ type: 'add' });
              }
            },
          },
          searchForm: {
            name: {
              type: "input",
              label: "曲谱名称",
              attrs: { placeholder: "曲谱名称", allowClear: true },
            },
            author: {
              type: "input",
              label: "作者",
              attrs: { placeholder: "作者", allowClear: true },
            },
            isRecommend: {
              type: "select",
              label: "是否热门",
              attrs: { placeholder: "是否热门", allowClear: true },
              datas: [{ label: "是", value: 1 }, { label: "否", value: 0 }],
            },
            isMelody: {
              type: "select",
              label: "是否旋律谱",
              attrs: { placeholder: "是否旋律谱", allowClear: true },
              datas: [{ label: "是", value: 1 }, { label: "否", value: 0 }],
            },
            cateId: {
              type: "select_tree",
              label: "曲谱分类",
              attrs: {
                placeholder: "曲谱分类",
                allowClear: true,
                fieldNames: {
                  label: 'name', value: 'id', children: 'children'
                }
              },
              datas: [],
            },
            approveStatus: {
              type: "select",
              label: "审核状态",
              attrs: { placeholder: "审核状态", allowClear: true },
              datas: approveStatus,
            },
            toExamine: {
              type: "select",
              label: "是否审核用",
              attrs: { placeholder: "是否审核用", allowClear: true },
              datas: [{ label: "是", value: 1 }, { label: "否", value: 0 }],
            },
          },
          service: musicScoreService,
          operation: ({ record }) => [
            {
              type: "edit",
              hidden: [1, 2].includes(record.approveStatus),
              permissions: "music:song:edit",
              clickHandler: () => {
                const addPopupRef = tablePageRef.value.getPopup("addRef");
                addPopupRef.value.open({ type: 'edit', id: record.id });
              }
            },
            {
              type: "add",
              hidden: [1, 2].includes(record.approveStatus),
              permissions: "music:song:play",
              text: record.lyricsData ? "重新打谱" : "打谱",
              clickHandler: () => {
                if (record.isMelody) {
                  router.push(`/musicScore/melodyAnalysis?id=${record.id}`);
                } else {
                  router.push(`/musicScore/disMelodyAnalysis?id=${record.id}`);
                }
              }
            },
            {
              type: "edit",
              permissions: "music:song:play",
              text: "修改曲谱",
              hidden: [1, 2].includes(record.approveStatus) || (record.isMelody && !record.chordsData) || (!record.isMelody && !record.lyricsData),
              clickHandler: () => {
                if (record.isMelody) {
                  router.push(`/musicScore/melodyAnalysis?id=${record.id}&modify=1`);
                } else {
                  router.push(`/musicScore/disMelodyAnalysis?id=${record.id}&modify=1`);
                }
              }
            },
            {
              type: "edit",
              hidden: !(record.approveStatus === 0 || record.approveStatus === 3),
              permissions: "music:song:approve:submit",
              icon: () => null,
              text: "提交审核",
              color: "primary",
              clickHandler: async () => {
                Modal.confirm({
                  title: "提示",
                  content: "确认提交审核?",
                  onOk: async () => {
                    const [err, res] = await to(musicScoreService.approveSubmit(record.id));
                    if (!err) {
                      message.success("提交成功");
                      tablePageRef.value.reload();
                    }
                  }
                })
              }
            },
            {
              type: "edit",
              hidden: !(record.approveStatus === 2),
              permissions: "music:song:approve:submit",
              icon: () => null,
              text: "作废审核",
              color: "danger",
              clickHandler: async () => {
                Modal.confirm({
                  title: "提示",
                  content: "确认作废审核?",
                  onOk: async () => {
                    const [err, res] = await to(musicScoreService.approveReback(record.id));
                    if (!err) {
                      message.success("提交成功");
                      tablePageRef.value.reload();
                    }
                  }
                })
              }
            },
            {
              type: "edit",
              hidden: !(record.approveStatus === 1),
              permissions: "music:song:approve:pass",
              icon: () => null,
              text: "审核通过",
              color: "success",
              clickHandler: async () => {
                Modal.confirm({
                  title: "提示",
                  content: "确认审核通过?",
                  onOk: async () => {
                    const [err, res] = await to(musicScoreService.approvePass(record.id));
                    if (!err) {
                      message.success("审核通过成功");
                      tablePageRef.value.reload();
                    }
                  }
                })
              }
            },
            {
              type: "edit",
              hidden: !(record.approveStatus === 1),
              permissions: "music:song:approve:unpass",
              icon: () => null,
              text: "审核不通过",
              color: "danger",
              clickHandler: async () => {
                Modal.confirm({
                  title: "提示",
                  content: "确认审核不通过?",
                  onOk: async () => {
                    const [err, res] = await to(musicScoreService.approveUnpass(record.id));
                    if (!err) {
                      message.success("已提交审核不通过");
                      tablePageRef.value.reload();
                    }
                  }
                })
              }
            },
            {
              type: "delete",
              hidden: [1, 2].includes(record.approveStatus),
              permissions: "music:song:remove",
              clickHandler: "delete",
            },
          ],
          bodyCell: ({ text, record, index, column }) => {
            if (column.dataIndex === "isRecommend") {
              return <>
                <IsRecommendSwitch record={record} value={Number(text)} onChange={() => tablePageRef.value.reload()} />
              </>
            }
            if (column.dataIndex === "isMelody") {
              return <span>{Number(text) === 1 ? "是" : "否"}</span>
            }
            if (column.dataIndex === "approveStatus") {
              return <>
                <ApproveStatus text={Number(text)} />
              </>
            }
            if (column.dataIndex === "status") {
              return <>
                <StatusSwitch record={record} value={Number(text)} onChange={() => tablePageRef.value.reload()} />
              </>
            }
            if (column.dataIndex === "toExamine") {
              return <>
                <ToExamineSwitch record={record} value={Number(text)} onChange={() => tablePageRef.value.reload()} />
              </>
            }
            if (column.dataIndex === "xmlFile") {
              return text ? <div class={styles.fileUrl} onClick={() => { downLoadUrl(text, '.xml', record) }}>{text}</div> : <span class={styles.noFile}>暂未上传xml文件</span>
            }
            if (column.dataIndex === "midFile") {
              return text ? <div class={styles.fileUrl} onClick={() => { downLoadUrl(text, '.mid', record) }}>{text}</div> : <span class={styles.noFile}>暂未上传mid文件</span>
            }
            if (column.dataIndex === "scoreTone") {
              return text ? <span>{text}</span> : <span class={styles.noFile}>暂无</span>
            }
            if (column.dataIndex === "chordTone") {
              return text ? <span>{text}</span> : <span class={styles.noFile}>暂无</span>
            }
            if (column.dataIndex === "lyricsData") {
              return text ? <a-button size="small" type="primary" onClick={() => { showJson(text) }}>查看</a-button> : <span class={styles.noFile}>暂未打谱</span>
            }
            if (column.dataIndex === "remark") {
              return text ? <Remark text={text} /> : <span class={styles.noFile}>暂无备注</span>
            }
          },
          popups: [
            {
              ref: "addRef",
              dom: () => <Add onChange={() => { tablePageRef.value.reload() }} />,
            },
            {
              ref: "jsonPreviewRef",
              dom: () => <JsonPreview />,
            }
          ],
          pagination: true,
          tableSourceFormat: {
            data: 'rows',
            pageSize: 'pageSize',
            current: 'pageNum',
          },
        }
      ],
    } as tablesInterface)
    // 配置项
    const config = reactive({
      table: tables.list[0],
    })
    // 获取曲谱分类树
    const getCatesTree = async () => {
      const [err, res]: any = await to(musicSongCategoryService.tree({ status: 0 }));
      if (!err) {
        (config.table.searchForm as any).cateId.datas = res.data?.data || [];
      }
    }
    // 下载文件
    const downLoadUrl = async (file_url: string, fileExtension: string, record: any) => {
      const [err, res] = await to(fetch(file_url));
      if (!err) {
        const blob = await res?.blob();
        // 创建一个指向Blob对象的URL
        const url = window.URL.createObjectURL(blob as any);
        // 创建一个隐藏的<a>元素
        const a = document.createElement('a');
        a.style.display = 'none';
        // 设置<a>元素的href属性为Blob对象的URL
        a.href = url;
        // 设置下载的文件名（可选，这里使用URL的最后一部分作为文件名）
        const filename = file_url.split('/').pop();
        a.download = filename || `untitled${fileExtension}`;
        // 将<a>元素添加到文档中（虽然它是隐藏的）
        document.body.appendChild(a);
        // 触发<a>元素的点击事件以下载文件
        a.click();
        // 释放URL对象（不再需要时）
        window.URL.revokeObjectURL(url);
      }
    }
    // 查看打谱json
    const showJson = (jsonStr: string) => {
      const jsonPreviewRef = tablePageRef.value.getPopup("jsonPreviewRef");
      jsonPreviewRef.value.open({
        title: "曲谱内容显示",
        jsonStr,
      });
    }
    onMounted(() => {
      getCatesTree();
      eventBus.analysisFinish.on(() => {
        tablePageRef.value.reload();
      })
    })
    onUnmounted(() => {
      eventBus.analysisFinish.off();
    })
    return () => (
      <div class={styles.musicScoreList}>
        <TablePage ref={tablePageRef} config={config} />
      </div>
    )
  }
})